package com.likuicat.picture_ddd.interfaces.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.likuicat.picture_ddd.infrastructure.annotation.AuthCheck;
import com.likuicat.picture_ddd.infrastructure.common.BaseResponse;
import com.likuicat.picture_ddd.infrastructure.common.ResultUtils;
import com.likuicat.picture_ddd.domain.user.constant.UserConstant;
import com.likuicat.picture_ddd.infrastructure.exception.BusinessException;
import com.likuicat.picture_ddd.infrastructure.exception.ErrorCode;
import com.likuicat.picture_ddd.infrastructure.api.CosManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Api(tags = "文件管理接口")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    @ApiOperation("通用文件上传")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", filename);
        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(filePath,null);
            //转为file
            multipartFile.transferTo(file);
            //上传文件
            cosManager.putObject(filePath,file);
            //返回
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error,filePath:{}", filePath);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败");
        }finally {
            if(file != null){
                boolean delete = file.delete();
                if(!delete){
                    log.error("file delete error,filePath:{}", filePath);
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR,"临时文件删除失败");
                }

            }
        }
    }

    @ApiOperation("下载文件")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void downloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            //处理下载的流对象
            byte[] byteArray = IOUtils.toByteArray(cosObjectInput);
            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            //写入响应
            response.getOutputStream().write(byteArray);
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("file download error,filePath:{}", filePath);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件下载失败");
        } finally {
            //关闭流
            if(cosObjectInput != null){
                cosObjectInput.close();
            }
        }
    }


}
